package com.app.bussinesslocator;

import java.util.ArrayList;
import java.util.Calendar;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.app.bussinesslocator.Utils.PreferenceHelper;
import com.app.bussinesslocator.adapter.ListOpenHourAdapter;
import com.app.bussinesslocator.bean.ObjBussiness;
import com.app.bussinesslocator.bean.ObjOpenHours;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class BussinessPageActivity extends Activity implements OnClickListener,
		LocationListener {

	Button btnBack;
	TextView txtNameBusiness, txtAddress;
	RatingBar ratingBar;

	Button btnGetDirection;
	TextView txtViewDetail;
	PreferenceHelper preferenceHelper;

	private GoogleMap googleMap;
	Location location;
	double mLatitude;
	double mLongitude;
	MarkerOptions markerOptions;
	TextView title;

	ObjBussiness objBussiness = new ObjBussiness();
	ObjOpenHours objOpenHours = new ObjOpenHours();
	ArrayList<ObjOpenHours> arr = new ArrayList<ObjOpenHours>();
	ArrayList<ObjOpenHours> arrSort = new ArrayList<ObjOpenHours>();
	ViewPager viewPager;
	ListOpenHourAdapter adapter;
//	CirclePageIndicator indicator;
	int pos;
	
	ListView listThoigian;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bussiness_page);

		preferenceHelper = new PreferenceHelper(this);

		objBussiness = getIntent().getParcelableExtra("objBusiness");
		Bundle b = getIntent().getExtras();

		if (b != null) {
			arr = (ArrayList<ObjOpenHours>) b.getSerializable("objOpenHour");
			System.out.println(arr);
		}
		for (int i = 0; i < arr.size(); i++) {
			Log.i("DATA", "Thu ngay: " + arr.get(i).getThoigianMocua());
		}

		btnBack = (Button) findViewById(R.id.btn_back);
		title = (TextView) findViewById(R.id.title);

		
		listThoigian = (ListView) findViewById(R.id.list_thoigianmocua);
		addHeader();
		
		/*viewPager = (ViewPager) findViewById(R.id.pager);
		indicator = (CirclePageIndicator) findViewById(R.id.indicator);*/

		Calendar c = Calendar.getInstance();
		int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
		String weekDay = null;
		int pos = 0;
		String[] thu = { "monday", "tuesday", "wednesday", "thursday",
				"friday", "saturday", "sunday" };

		Log.i("DATA", "Vi tri: " + dayOfWeek);
		switch (dayOfWeek) {
		case 1:
			weekDay = "sunday";
			break;
		case 2:
			weekDay = "monday";
			break;
		case 3:
			weekDay = "tuesday";
			break;
		case 4:
			weekDay = "wednesday";
			break;
		case 5:
			weekDay = "thursday";
			break;
		case 6:
			weekDay = "friday";
			break;
		case 7:
			weekDay = "saturday";
			break;
		default:
			break;
		}

		/*
		 * for (int i = 0; i < arr.size(); i++) { if
		 * (weekDay.equals(arr.get(i).getThuNgay())){ pos = i; } }
		 */

		for (int i = 0; i < arr.size(); i++) {
			if (arr.get(i).getThuNgay().equals(thu[0])) {
				arrSort.add(0, arr.get(i));
			}
		}
		for (int i = 0; i < arr.size(); i++) {
			if (arr.get(i).getThuNgay().equals(thu[1])) {
				arrSort.add(1, arr.get(i));
			}
		}
		for (int i = 0; i < arr.size(); i++) {
			if (arr.get(i).getThuNgay().equals(thu[2])) {
				arrSort.add(2, arr.get(i));
			}
		}
		for (int i = 0; i < arr.size(); i++) {
			if (arr.get(i).getThuNgay().equals(thu[3])) {
				arrSort.add(3, arr.get(i));
			}
		}
		for (int i = 0; i < arr.size(); i++) {
			if (arr.get(i).getThuNgay().equals(thu[4])) {
				arrSort.add(4, arr.get(i));
			}
		}
		for (int i = 0; i < arr.size(); i++) {
			if (arr.get(i).getThuNgay().equals(thu[5])) {
				arrSort.add(5, arr.get(i));
			}
		}
		for (int i = 0; i < arr.size(); i++) {
			if (arr.get(i).getThuNgay().equals(thu[6])) {
				arrSort.add(6, arr.get(i));
			}
		}
		
		for (int i = 0; i < arrSort.size(); i++) {
			if(weekDay.equals(arrSort.get(i).getThuNgay())){ 
				pos = i;
			}
		}
		
		adapter = new ListOpenHourAdapter(BussinessPageActivity.this, arrSort);
		/*viewPager.setAdapter(adapter);
		viewPager.setPageMargin(20);*/
		listThoigian.setAdapter(adapter);
		listThoigian.setSelection(0);
//		HelperListview.getListViewSize(listThoigian);
		

		Log.i("DATA", "Thu: " + weekDay + " " + pos);


		init();

		setData();
		
		// Getting status
				int status = GooglePlayServicesUtil
						.isGooglePlayServicesAvailable(getBaseContext());

				// Showing status
				if (status == ConnectionResult.SUCCESS) {
					/*Toast.makeText(FindNearActivity.this,
							"Google Play Services are available", Toast.LENGTH_SHORT)
							.show();*/
					setUpMap();
					focusBussinessLocaation();
				} else {
					Toast.makeText(BussinessPageActivity.this,
							"Google Play Services are not available",
							Toast.LENGTH_SHORT).show();
					int requestCode = 10;
					Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
							requestCode);
					dialog.show();
				}
	}

	
	void focusBussinessLocaation(){
		LatLng latLng = new LatLng(objBussiness
				.getLatitude(), objBussiness.getLongitude());
		googleMap.moveCamera(CameraUpdateFactory
				.newLatLng(latLng));
		googleMap.animateCamera(CameraUpdateFactory
				.zoomTo(12));
	}
	
	
	void setData() {
		txtNameBusiness.setText(objBussiness.getBussinessName());
		txtAddress.setText(objBussiness.getAddress());
		ratingBar.setRating(objBussiness.getOverall());
		title.setText(objBussiness.getBussinessName());
	}

	void init() {
		btnBack.setOnClickListener(this);
		txtViewDetail.setOnClickListener(this);
		btnGetDirection.setOnClickListener(this);
	}
	
	private void addHeader() {
		LayoutInflater inflater = getLayoutInflater();
		ViewGroup v = (ViewGroup) inflater.inflate(
				R.layout.header_business, listThoigian, false);
		txtNameBusiness = (TextView) v.findViewById(R.id.txt_name_business);
		txtAddress = (TextView) v.findViewById(R.id.txt_address);
		ratingBar = (RatingBar) v.findViewById(R.id.ratingBar);
		txtViewDetail = (TextView) v.findViewById(R.id.txt_view_detail);
		btnGetDirection = (Button) v.findViewById(R.id.btn_get_direction);
		
		listThoigian.addHeaderView(v, null, false);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			finish();
			break;
		case R.id.txt_view_detail:
			gotoViewRatingDetail();
			break;
		case R.id.btn_get_direction:
			gotoDirection();
			break;
		default:
			break;
		}
	}

	void gotoViewRatingDetail() {
		Intent t = new Intent(BussinessPageActivity.this,
				DetailRatingActivity.class);
		t.putExtra("objBusiness", objBussiness);
		startActivity(t);
	}

	void gotoDirection() {
		Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
				Uri.parse("http://maps.google.com/maps?   saddr="
						+ preferenceHelper.getLAT() + ","
						+ preferenceHelper.getLON() + "&daddr="
						+ objBussiness.getLatitude() + ","
						+ objBussiness.getLongitude()));
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);
		intent.setClassName("com.google.android.apps.maps",
				"com.google.android.maps.MapsActivity");
		try {
			startActivity(intent);
		} catch (ActivityNotFoundException ex) {
			try {
				Intent unrestrictedIntent = new Intent(Intent.ACTION_VIEW,
						Uri.parse("http://maps.google.com/maps?   saddr="
								+ preferenceHelper.getLAT() + ","
								+ preferenceHelper.getLON() + "&daddr="
								+ objBussiness.getLatitude() + ","
								+ objBussiness.getLongitude()));
				startActivity(unrestrictedIntent);
			} catch (ActivityNotFoundException innerEx) {
				Toast.makeText(this, "Please install a maps application",
						Toast.LENGTH_LONG).show();
			}
		}
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@SuppressLint("NewApi")
	private void setUpMap() {
		// Do a null check to confirm that we have not already instantiated the
		// map.
		if (googleMap == null) {
			// Try to obtain the map from the SupportMapFragment.
			googleMap = ((MapFragment) getFragmentManager().findFragmentById(
					R.id.map)).getMap();

			
			
			// Check if we were successful in obtaining the map.

			// Enabling MyLocation in Google Map
			googleMap.setMyLocationEnabled(true);
			googleMap.getUiSettings().setMyLocationButtonEnabled(true);
			
			LatLng locationBussiness = new LatLng(objBussiness.getLatitude(),
					objBussiness.getLongitude());

			Marker marker = googleMap.addMarker(new MarkerOptions().position(
					locationBussiness).icon(
					BitmapDescriptorFactory.fromResource(R.drawable.problem)));

			// Getting LocationManager object from System Service
			// LOCATION_SERVICE
			LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

			// Creating a criteria object to retrieve provider
			Criteria criteria = new Criteria();

			// Getting the name of the best provider
			String provider = locationManager.getBestProvider(criteria, true);

			// Getting Current Location From GPS
			location = locationManager.getLastKnownLocation(provider);

			if (location != null) {
				onLocationChanged(location);
			}

			locationManager.requestLocationUpdates(provider, 1000, 0,
					new android.location.LocationListener() {

						@Override
						public void onStatusChanged(String provider,
								int status, Bundle extras) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onProviderEnabled(String provider) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onProviderDisabled(String provider) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onLocationChanged(Location location) {
							// TODO Auto-generated method stub
							mLatitude = (float) location.getLatitude();
							mLongitude = (float) location.getLongitude();
							LatLng latLng = new LatLng(objBussiness
									.getLatitude(), objBussiness.getLongitude());

							Log.i("DATA", "LAT: " + mLatitude + "LONG: "
									+ mLongitude);

							googleMap.moveCamera(CameraUpdateFactory
									.newLatLng(latLng));
							googleMap.animateCamera(CameraUpdateFactory
									.zoomTo(12));
						}
					});
		}
	}
}
